package com.tengfei.adapterdemo.adapter;

import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.tengfei.adapterdemo.R;
import com.tengfei.adapterdemo.entry.ReceiveData;
import com.tengfei.adapterdemo.util.HttpUtil;

import java.util.List;

public class MyListViewAdapter extends BaseAdapter {

    private List<ReceiveData.PhotoData> mDatas;
    private int mScreenWidth;


    public MyListViewAdapter(List<ReceiveData.PhotoData> datas, int screenWitdh) {
        mDatas = datas;
        mScreenWidth = screenWitdh;
    }

    @Override
    public int getCount() {
        if (mDatas == null) {
            return 0;
        }
        return mDatas.size();
    }

    @Override
    public ReceiveData.PhotoData getItem(int i) {
        return mDatas.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        View rootview = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_photo, null, true);
        ImageView imageview = rootview.findViewById(R.id.iv_1);
        TextView textview = rootview.findViewById(R.id.tv_1);
        // 加载图片
        load_photo(getItem(i).getImg(), imageview);
        textview.setText(getItem(i).getTime());
        return rootview;
    }

    private void load_photo(final String img_url, final ImageView imageview) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final Bitmap bitmap = HttpUtil.doBitmap(img_url);
                if (bitmap != null) {
                    int showHeight = (int) ((float) bitmap.getHeight() / bitmap.getWidth() * mScreenWidth);
                    ViewGroup.LayoutParams params = imageview.getLayoutParams();
                    params.width = mScreenWidth;
                    params.height = showHeight;
                }
                // 跳转到主线程
                imageview.post(new Runnable() {
                    @Override
                    public void run() {
                        imageview.setImageBitmap(bitmap);
                    }
                });
            }
        }).start();
    }


}
